<template>
  <div class="media">
    <!-- <el-radio-group
      v-model="propMedia"
      @change="changeCategory"
    >
      <el-radio
        :disabled="disabled"
        v-for="item in GENERALIZE_CELL_MEDIA_TYPE"
        :label="item.value"
        :key="item.value"
      >{{item.label}}</el-radio>
    </el-radio-group> -->
    <div class="transfer">
      <div class="transfer-panel transfer-source">
        <el-form
          inline
          class="transfer-panel__hd"
        >
          <!-- 按adx -->
          <template v-if="propMedia === 0">
            <el-form-item>
              <el-select
                v-model="adMarketValue"
                filterable
                size="small"
                placeholder="请选择交易市场"
                :style="{width: '400px'}"
                @change="changeAdxMarket(adMarketValue)"
              >
                <el-option
                  v-for="item in adMarketOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </template>
          <!-- 按广告位 -->
          <template v-if="propMedia === 3">
            <el-form-item>
              <el-select
                v-model="adMarketValue"
                filterable
                size="small"
                placeholder="请选择交易市场"
                :style="{width: '130px'}"
                @change="changeSpaceMarket(adMarketValue)"
              >
                <el-option
                  v-for="item in adMarketOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select
                v-model="adMediaValue"
                filterable
                size="small"
                placeholder="请选择媒体"
                :style="{width: '130px'}"
                @change="changeSpaceMedia(adMediaValue)"
              >
                <el-option
                  v-for="item in adMediaOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select
                v-model="adLocalValue"
                filterable
                size="small"
                placeholder="请选择广告位类型"
                :style="{width: '130px'}"
                @change="changeSpaceLocal(adLocalValue)"
              >
                <el-option
                  v-for="item in adLocalOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-form>
        <div class="transfer-panel__bd">
          <el-tree
            ref="soureTree"
            accordion
            :props="treeProps"
            :data="soureData"
            show-checkbox
            node-key="id"
            @check="selectTree"
          >
          </el-tree>
        </div>
      </div>
      <!-- <el-button
        class="transfer-button"
        icon="el-icon-arrow-right"
        circle
      ></el-button>
      <div class="transfer-panel transfer-target">
        <el-row class="transfer-panel__hd">
          <el-col :span="12">已选</el-col>
          <el-col
            :span="12"
            align="right"
          >
            <el-button
              v-show="targetData.length && !disabled"
              size="mini"
              type="text"
              @click="clearTree"
            >
              清空
            </el-button>
          </el-col>
        </el-row>
        <div class="transfer-panel__bd">
          <el-tree
            accordion
            :data="targetData"
            :props="treeProps"
            node-key="id"
            :render-content="renderTarget"
          >
          </el-tree>
        </div>
      </div> -->
    </div>
  </div>
</template>

<script>
import { cloneDeep } from "lodash";

import { GENERALIZE_CELL_MEDIA_TYPE } from "@/assets/js/common-option";
import { fetchAdxSelect, fetchAdLocalSelect } from "@/api";
export default {
  name: "DropMedia",
  props: {
    media: {
      type: Number,
      default: 3
    },
    mediaValue: String,
    mediaEcho: {
      type: String,
      default: "0,0,0,0"
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      GENERALIZE_CELL_MEDIA_TYPE,

      // 下拉数据
      cascadeData: [],
      adMarketOptions: [],
      adMediaTypeOptions: [],
      adMediaOptions: [],
      adLocalOptions: [],
      adMarketValue: this.mediaEcho.split(",")[0] || "0",
      adMediaTypeValue: this.mediaEcho.split(",")[1] || "0",
      adMediaValue: this.mediaEcho.split(",")[2] || "0",
      adLocalValue: this.mediaEcho.split(",")[3] || "0",

      // 属性值
      propMedia: this.media,
      propValue: this.mediaValue,
      propSelect: this.mediaEcho,

      // 树
      treeProps: {
        label: "name"
      },
      soureData: [],
      targetData: [],
      selectTreeID: []
    };
  },
  watch: {
    mediaEcho(v) {
      this.propSelect = v;
      this.initSelectValue(v);
      this.initSelectTree();
    },
    mediaValue(v) {
      this.propValue = v;
      if (v) {
        this.selectTreeID = this.getCheckedKeys(v.split(/,|__/)); // 多个分隔符为了兼容历史数据格式
        this.setTreeData();
      }
    }
  },
  methods: {
    // 数据
    fetchAdxSelect() {
      return fetchAdxSelect({
        query: {
          unionId: 0 // adx，默认
        }
      }).then(res => {
        this.cascadeData = res.data.list.map(item => {
          return {
            id: String(item.id),
            name: item.name
          };
        });
      });
    },
    fetchAdLocalSelect(params = {}) {
      return fetchAdLocalSelect({
        query: Object.assign(
          {
            unionId: 0, // adx
            mediaId: 0, // 媒体
            adspaceType: 0 // 创意形式，默认
          },
          params
        )
      }).then(res => {
        this.cascadeData = res.data.list;
      });
    },
    // 初始化数据
    initData() {
      switch (this.propMedia) {
        case 0:
          this.fetchAdxSelect().then(() => {
            this.initSelect();
          });
          break;
        case 3:
          this.fetchAdLocalSelect().then(() => {
            this.initSelect();
          });
          break;
      }
    },
    // 初始化下拉选中值
    initSelectValue(select) {
      let sel = select.split(",");
      this.adMarketValue = sel[0];
      this.adMediaTypeValue = sel[1];
      this.adMediaValue = sel[2];
      this.adLocalValue = sel[3];
    },
    // 初始化下拉树
    initSelectTree() {
      switch (this.propMedia) {
        case 0:
          var adx = this.getAdxOptions(this.cascadeData, this.adMarketValue);
          this.adMarketOptions = this.getAdxOptions(this.cascadeData).adx;
          this.setSoureData(adx.tree);
          break;
        case 3:
          var space = this.getSpaceOptions(
            this.cascadeData,
            this.adMarketValue,
            this.adMediaValue,
            this.adLocalValue
          );
          this.setSoureData(space.tree);
          this.adMarketOptions = this.getSpaceOptions(this.cascadeData).adx;
          this.adMediaOptions = this.getSpaceOptions(
            this.cascadeData,
            this.adMarketValue
          ).media;
          this.adLocalOptions = this.getSpaceOptions(
            this.cascadeData,
            this.adMarketValue,
            this.adMediaValue
          ).space;
          break;
      }
    },
    // 初始化下拉选项和树
    initSelect() {
      switch (this.propMedia) {
        case 0:
          var adx = this.getAdxOptions(this.cascadeData, this.adMarketValue);
          this.setSoureData(adx.tree);
          this.adMarketOptions = adx.adx;
          break;
        case 3:
          var space = this.getSpaceOptions(
            this.cascadeData,
            this.adMarketValue,
            this.adMediaValue,
            this.adLocalValue
          );
          this.setSoureData(space.tree);
          this.adMarketOptions = space.adx;
          this.adMediaOptions = space.media;
          this.adLocalOptions = space.space;
          break;
      }
    },
    // 切换分类
    changeCategory() {
      // 重置下拉
      this.initSelectValue("0,0,0,0");
      this.initData();
      this.clearTree();
    },
    // 按adx选择/交易市场
    changeAdxMarket(id) {
      let ret = this.getAdxOptions(this.cascadeData, id);
      this.setSoureData(ret.tree);
    },
    // 按广告位选择/交易市场
    changeSpaceMarket(id) {
      let ret = this.getSpaceOptions(this.cascadeData, id);
      this.setSoureData(ret.tree);
      this.adMediaOptions = ret.media;
      this.adLocalOptions = ret.space;
      this.adMediaValue = "0";
      this.adLocalValue = "0";
    },
    // 按广告位选择/媒体
    changeSpaceMedia(id) {
      let ret = this.getSpaceOptions(this.cascadeData, this.adMarketValue, id);
      this.setSoureData(ret.tree);
      this.adLocalOptions = ret.space;
      this.adLocalValue = "0";
    },
    // 按广告位选择/广告位
    changeSpaceLocal(id) {
      let ret = this.getSpaceOptions(
        this.cascadeData,
        this.adMarketValue,
        this.adMediaValue,
        id
      );
      this.setSoureData(ret.tree);
    },
    // 设置树数据
    setSoureData(data) {
      this.soureData = this.setTreeDisabled(data);
    },
    // 设置树disabled
    setTreeDisabled(data) {
      data.forEach(item => {
        item.disabled = this.disabled;
        if (item.children && item.children.length) {
          this.setTreeDisabled(item.children);
        }
      });
      return data;
    },
    getCheckedKeys(ids = []) {
      // 市场id2位、媒体3位、广告位pid_开头
      let ret = {
        adx: [],
        media: [],
        space: []
      };
      ids.forEach(id => {
        if (id.startsWith("pid_")) {
          ret.space.push(id);
        } else if (id.length === 2) {
          ret.adx.push(id);
        } else if (id.length === 3) {
          ret.media.push(id);
        }
      });
      switch (this.propMedia) {
        case 0:
          return ret.adx;
        case 3:
          return ret.space;
      }
      return [];
    },
    // 计算广告位建议出价
    getSuggestSpacePrice(data) {
      let ret = {
        min: [],
        max: [],
        limit: 0
      };
      data.forEach(adx => {
        adx.children.forEach(media => {
          media.children.forEach(space => {
            if (space.limitPrice) {
              let range = space.limitPrice.split("-");
              ret.min.push(Number(range[0]));
              ret.max.push(Number(range[1]));
              ret.limit++;
            }
          });
        });
      });
      let res = "";
      if (ret.limit) {
        res = `${Math.min.apply([], ret.min)}~${Math.max.apply([], ret.max)}`;
      }
      this.$emit("space-price", res);
    },
    // 选中树
    setTreeData() {
      let checkedParent = this.getTreeParentIds(this.selectTreeID);
      this.$refs.soureTree.setCheckedKeys(this.selectTreeID);
      this.targetData = this.getTargetData(checkedParent);
      this.getSuggestSpacePrice(this.targetData);
    },
    // 选择树
    selectTree(current, { checkedKeys }) {
      let isChecked = checkedKeys.some(id => id === current.id);
      // 取消选中
      if (!isChecked) {
        // 过滤已保存的选项
        this.selectTreeID = this.removeTreeCancelId(current);
      }
      this.selectTreeID = this.selectTreeID.concat(
        this.getCheckedKeys(checkedKeys)
      );
      this.setTreeData();
      this.updateNotice();
    },
    // 删除取消的id
    removeTreeCancelId(data) {
      let ids = [];
      // 是父节点时找出所有他的子节点
      if (data.children) {
        ids = this.getTreeChildId(data);
      } else {
        ids = [data.id];
      }
      return this.selectTreeID.filter(id => ids.indexOf(id) === -1);
    },
    // 获取子树所有节点id
    getTreeChildId(tree, child = []) {
      if (!tree.children) {
        child.push(tree.id);
      } else {
        tree.children.forEach(item => {
          this.getTreeChildId(item, child);
        });
      }
      return child;
    },
    // 获取选中树所有父节点id
    getTreeParentId(data, value) {
      let findMap = (data, ids, map = {}) => {
        data.forEach(item => {
          map[item.id] = map[item.id] || [];
          if (ids) {
            map[item.id] = ids.concat(item.id);
          } else {
            map[item.id].push(item.id);
          }
          if (item.children) {
            return findMap(item.children, map[item.id], map);
          }
        });
        return map;
      };
      return findMap(data)[value];
    },
    getTreeParentIds(ids) {
      let ret = [];
      ids.forEach(id => {
        ret = ret.concat(this.getTreeParentId(this.cascadeData, id));
      });
      return [...new Set(ret)];
    },
    // 获取选中树
    getTargetData(ids) {
      let data = cloneDeep(this.cascadeData);
      // 删除未选中数据
      let remove = (data, ids) => {
        for (let i = 0; i < data.length; i++) {
          if (ids.indexOf(data[i].id) === -1) {
            data.splice(i, 1);
            i--;
          } else {
            if (data[i].children && data[i].children.length) {
              remove(data[i].children, ids);
            }
          }
        }
      };
      remove(data, ids);
      return data;
    },
    // 清空选中树
    clearTree() {
      this.$refs.soureTree.setCheckedKeys([]);
      this.selectTreeID = [];
      this.targetData = [];
      this.updateNotice();
    },
    // 树删除项
    remove(node, data) {
      this.removeTreeItem(this.targetData, data.id);
      this.$refs.soureTree.setChecked(data.id, false, true);
      // 过滤已保存的选项
      this.selectTreeID = this.removeTreeCancelId(data);
      this.updateNotice();
    },
    removeTreeItem(tree, id) {
      for (let i = 0; i < tree.length; i++) {
        if (
          (tree[i].children && !tree[i].children.length) ||
          tree[i].id === id
        ) {
          tree.splice(i, 1);
          i--;
        } else {
          if (tree[i].children && tree[i].children.length) {
            this.removeTreeItem(tree[i].children, id);
          }
        }
      }
    },
    renderTarget(h, { node, data }) {
      if (this.disabled) {
        return (
          <div class="transfer-target-tree">
            <div class="transfer-target-tree__label">{node.label}</div>
          </div>
        );
      }
      return (
        <div class="transfer-target-tree">
          <div class="transfer-target-tree__label">{node.label}</div>
          <el-button
            size="mini"
            type="text"
            class="transfer-target-tree__remove"
            on-click={() => this.remove(node, data)}
          >
            删除
          </el-button>
        </div>
      );
    },
    // 更新通知
    updateNotice() {
      let mediaValue = [...new Set(this.selectTreeID)].join();
      this.$emit(
        "change",
        mediaValue,
        this.propMedia,
        `${this.adMarketValue},${this.adMediaTypeValue},${this.adMediaValue},${this.adLocalValue}`
      );
    },
    // 按adx选择
    getAdxOptions(tree = [], adxValue = "0") {
      let ret = {
        tree: cloneDeep(tree),
        adx: [{ id: "0", name: "全部交易市场" }]
      };
      if (adxValue === "0") {
        ret.tree = tree;
      } else {
        ret.tree = tree.filter(adx => adx.id === adxValue);
      }
      ret.adx = ret.adx.concat(ret.tree);
      return ret;
    },
    /**
     * 按广告位选择的树和下拉数据
     * @params tree <Array> 树数据
     * @params adxValue <String> 市场选中的id，默认0表示全部
     * @params adMediaValue <String> 媒体选中的id，默认0表示全部
     * @params spaceValue <String> 广告位选中的id，默认0表示全部（后端id是String）
     */
    getSpaceOptions(
      tree = [],
      adxValue = "0",
      adMediaValue = "0",
      spaceValue = "0"
    ) {
      let ret = {
        tree: cloneDeep(tree),
        adx: [{ id: "0", name: "全部交易市场" }],
        media: [{ id: "0", name: "全部媒体" }],
        space: [{ id: "0", name: "全部广告位" }]
      };
      // 剔除不满足条件的广告位
      ret.tree.forEach(adx => {
        if (adx.children) {
          adx.children.filter(media => {
            if (media.children) {
              media.children = media.children.filter(
                space => space.id === spaceValue || spaceValue === "0"
              );
            }
          });
        }
      });
      // 剔除不满足条件的媒体
      ret.tree.forEach(adx => {
        if (adx.children) {
          adx.children = adx.children.filter(media => {
            if (media.children && media.children.length) {
              return media.id === adMediaValue || adMediaValue === "0";
            }
            return false;
          });
        }
      });
      // 剔除不满足条件的市场
      ret.tree = ret.tree.filter(adx => {
        if (adx.children && adx.children.length) {
          return adx.id === adxValue || adxValue == "0";
        }
        return false;
      });
      // 获取下拉数据
      ret.tree.forEach(adx => {
        if (adx.id === adxValue || adxValue === "0") {
          ret.adx.push({ id: adx.id, name: adx.name });
        }
        if (adx.children) {
          adx.children.forEach(media => {
            if (media.id === adMediaValue || adMediaValue === "0") {
              ret.media.push({ id: media.id, name: media.name });
            }
            if (media.children) {
              media.children.forEach(space => {
                if (space.id === spaceValue || spaceValue === "0") {
                  ret.space.push({ id: space.id, name: space.name });
                }
              });
            }
          });
        }
      });
      return ret;
    }
  },
  created() {
    this.initData();
  }
};
</script>
<style lang="scss">
.transfer-target-tree {
  position: relative;
  width: 100%;
  font-size: 14px;
  padding-right: 40px;
  &__label {
    width: 154px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
  &__remove {
    position: absolute;
    top: 6px;
    right: 8px;
  }
}
</style>
<style lang="scss" scoped>
@import "~@/assets/scss/color";
.transfer {
  position: relative;
  &-panel {
    display: inline-block;
    // height: 311px;
    padding-bottom: 10px;
    background: $--background-high;
    &__hd {
      padding: 5px 10px;
      border-bottom: 1px solid $--border-major;
    }
    &__bd {
      padding: 5px 0;
      height: 260px;
      overflow: auto;
    }
    border: 1px solid $--border-major;
  }
  &-source {
    // width: 420px;
    width: 732px;
  }
  &-target {
    width: 258px;
    margin-left: 50px;
  }
  &-button {
    position: absolute;
    top: 140px;
    left: 432px;
    padding: 7px;
  }
}
.transfer {
  .el-form--inline .el-form-item {
    margin-right: 5px !important;
  }
  .el-form--inline .el-form-item:last-child {
    margin-right: 0 !important;
  }
}
</style>
